package testBingMap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;

public class TestBingMap {
	
	private static final String MSG_CITY_AND_STATE_OR_ZIP_CODE_REQUIRED = "cityAndStateOrZipCodeRequired";
	private static final String MSG_ZIPCODE_LENGTH_AND_TYPE = "ZIP Code must be 5 characters and must be numeric";
	private static final String EMPTY = "";
	private static final String ZIPCODE_REGEX = "\\d{5}";
	private static final Integer NUMBER_OF_PHARMACIES_REQUESTED_MOCK = 10;
	private static final Double KILOMETERS_MILES_RATE = 1.6093;
	private static final Integer SECONDS_PER_HOUR = 3600;
	private static final Integer MINIUTES_PER_HOUR = 60;
	private static final Integer STATE_INRANGE_DEFAULT = 5;
	private static final String YES = "Y";
	private static final String NO = "N";
	
	@Test
	public void testBing() {
				Member member = new Member();
				//bing
				StringBuilder builder = new StringBuilder();
				member.setAddress1("KANSAS");
				String startAddress = member.getAddress1();
				
				PharmInfoImpl pharmInfo = new PharmInfoImpl();
				pharmInfo.setZipCode("64111");
				pharmInfo.setAddressLine1("3845 Broadway St");
				pharmInfo.setCity("KANSAS");
				pharmInfo.setState("MO");
				
				String endAddress = builder.append(pharmInfo.getZipCode()).append(",")
						.append(pharmInfo.getAddressLine1()).append("/")
						.append(pharmInfo.getCity()).append("/").append(pharmInfo.getState())
						.append("/").toString();
				System.out.println("endAddress:"+endAddress);
				Map<String, List<String>> mapDistanceAndDirection = new HashMap<String, List<String>>();
				try { 
//					mapDistanceAndDirection = getRouteDirectionAndDistanceAndEstimtedTime("65014", endAddress);
					//Railroad Ave Bland, MO 65014 | Ray St Bland, MO 65014
					long startTime = System.currentTimeMillis();
					mapDistanceAndDirection = getRouteDirectionAndDistanceAndEstimtedTime("65014", "Ray St Bland, MO 65014");
					long endTime = System.currentTimeMillis();
					System.out.println(endTime-startTime);
				} catch (URISyntaxException e) {
				} catch (IOException e) {
				}
				List<String> directions = mapDistanceAndDirection.get("directions");
				String totalDistances = mapDistanceAndDirection.get("totalDistances").get(0);
				String totalEstimatedDrivingTimes = mapDistanceAndDirection.get("totalEstimatedDrivingTimes").get(0);
				System.out.println(directions);
				System.out.println(totalDistances);
				System.out.println(totalEstimatedDrivingTimes);

	}

	/**
	 * 
	 * @param startAddress
	 * @param endAddress
	 * @return
	 * @throws URISyntaxException
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	private Map<String, List<String>> getRouteDirectionAndDistanceAndEstimtedTime(
			String startAddress, String endAddress) throws URISyntaxException,
			 IOException {
//		String s1 = startAddress.replaceAll(" ", "%20");		
//		String s2 = endAddress.replaceAll(" ", "%20");startAddress.replaceAll(" ", "%20")
		// %20 represent the space
		String requestUri = "http://dev.virtualearth.net/REST/v1/Routes?wp.0="
				+ startAddress.replaceAll(" ", "%20")
				+ "&wp.1="
				+ endAddress.replaceAll(" ", "%20")
				+ "&routePathOutput=Points&output=json&key=AlBHPfpX9T4DUhBS0I" 
				+ "xE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
		URI uri = new URI(requestUri);
		HttpGet get = new HttpGet(uri);
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response = httpclient.execute(get);
		StatusLine st = response.getStatusLine();
		if (st.getStatusCode() == HttpServletResponse.SC_OK) {
			InputStream ins = response.getEntity().getContent();

			BufferedReader br = new BufferedReader(new InputStreamReader(ins));
			StringBuilder sb = new StringBuilder();
			int i = 0;
			String b = br.readLine();
			while (b != null) {
				i++;
				sb.append(b);
				b = br.readLine();
			}
			JSONObject json = JSONObject.fromObject(sb.toString());
			System.out.println(json);
			int itemsSize = json.getJSONArray("resourceSets").getJSONObject(0)
					.getJSONArray("resources").getJSONObject(0)
					.getJSONArray("routeLegs").getJSONObject(0)
					.getJSONArray("itineraryItems").size();
			List<String> directions = new ArrayList<String>();
			List<String> perDistances = new ArrayList<String>();
			List<String> totalDistances = new ArrayList<String>();
			List<String> perEstimatedDrivingTimes = new ArrayList<String>();
			List<String> totalEstimatedDrivingTimes = new ArrayList<String>();

			Double totalDistanceKilometers = 0.00;
			Long totalEstimatedDrivingTime = 0L;
			for (int j = 0; j < itemsSize; j++) {
				// distance of pharmacy
				Double perDistanceKilometers = Double.valueOf(json
						.getJSONArray("resourceSets").getJSONObject(0)
						.getJSONArray("resources").getJSONObject(0)
						.getJSONArray("routeLegs").getJSONObject(0)
						.getJSONArray("itineraryItems").getJSONObject(j)
						.get("travelDistance").toString());
				BigDecimal bigDistance = new BigDecimal(
						perDistanceKilometers / KILOMETERS_MILES_RATE);
				Double doubledistanceMile = bigDistance.setScale(1,
						BigDecimal.ROUND_HALF_UP).doubleValue();
				String perStringdistanceMile = String
						.valueOf(doubledistanceMile);
				perDistances.add(perStringdistanceMile);
				// total distance
				totalDistanceKilometers = totalDistanceKilometers
						+ perDistanceKilometers;

				// dirving Direction
				String perDirection = json.getJSONArray("resourceSets")
						.getJSONObject(0).getJSONArray("resources")
						.getJSONObject(0).getJSONArray("routeLegs")
						.getJSONObject(0).getJSONArray("itineraryItems")
						.getJSONObject(j).getJSONObject("instruction")
						.get("text").toString();
				directions.add(perDirection);

				// EstimatedDrivingTime
				String perEstimatedDrivingTime = json
						.getJSONArray("resourceSets").getJSONObject(0)
						.getJSONArray("resources").getJSONObject(0)
						.getJSONArray("routeLegs").getJSONObject(0)
						.getJSONArray("itineraryItems").getJSONObject(j)
						.get("travelDuration").toString();
				Long longperEstimatedDrivingTime = Long
						.valueOf(perEstimatedDrivingTime);
				totalEstimatedDrivingTime = totalEstimatedDrivingTime
						+ longperEstimatedDrivingTime;
			}
			
			//total totalDistances
			BigDecimal bigDistance = new BigDecimal(
					totalDistanceKilometers / KILOMETERS_MILES_RATE);
			Double doubledistanceMile = bigDistance.setScale(1,
					BigDecimal.ROUND_HALF_UP).doubleValue();
			String totalStringdistanceMile = String.valueOf(doubledistanceMile);
			totalDistances.add(totalStringdistanceMile);

			// total estimatedDrivingtime
			Integer hour = (int) Math.abs(totalEstimatedDrivingTime / SECONDS_PER_HOUR);
			Integer minute = (int) Math
					.abs(totalEstimatedDrivingTime / SECONDS_PER_HOUR / MINIUTES_PER_HOUR);
			String totalStringEstimatedDrivingTime = new StringBuilder()
					.append(hour).append("hours").append(",").append(minute)
					.append("minutes").toString();
			totalEstimatedDrivingTimes.add(String
					.valueOf(totalStringEstimatedDrivingTime));

			Map<String, List<String>> mapDistanceAndDirection = new HashMap<String, List<String>>();

			
			mapDistanceAndDirection.put("directions", directions);
			mapDistanceAndDirection.put("perDistances", perDistances);
			mapDistanceAndDirection.put("totalDistances", totalDistances);
			mapDistanceAndDirection.put("estimatedDrivingTimes",
					perEstimatedDrivingTimes);
			mapDistanceAndDirection.put("totalEstimatedDrivingTimes",
					totalEstimatedDrivingTimes);
			return mapDistanceAndDirection;
		} else {
			return null;
		}
	}
	
	
	@Test
	public void  getPoint() throws URISyntaxException,
		 IOException {
//	String s1 = startAddress.replaceAll(" ", "%20");		
//	String s2 = endAddress.replaceAll(" ", "%20");startAddress.replaceAll(" ", "%20")
	// %20 represent the space
//	String requestUri = "http://dev.virtualearth.net/REST/v1/Routes?wp.0="
//			+ "NewYork".replaceAll(" ", "%20")
//			+ "&routePathOutput=Points&output=json&key=AlBHPfpX9T4DUhBS0I" 
//			+ "xE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
//	URI uri = new URI(requestUri);
		// with 
		String address = "MO".replace(" ", "%20");
	String requestUri2 = "http://dev.virtualearth.net/REST/v1/Locations/"+address+"?key=AlBHPfpX9T" +
			"4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
	System.out.println("aaaaaaa------------"+requestUri2);
	URI uri2 = new URI(requestUri2);
	HttpGet get = new HttpGet(uri2);
	HttpClient httpclient = new DefaultHttpClient();
	HttpResponse response = httpclient.execute(get);
	StatusLine st = response.getStatusLine();
	if (st.getStatusCode() == HttpServletResponse.SC_OK) {
		InputStream ins = response.getEntity().getContent();

		BufferedReader br = new BufferedReader(new InputStreamReader(ins));
		StringBuilder sb = new StringBuilder();
		int i = 0;
		String b = br.readLine();
		while (b != null) {
			i++;
			sb.append(b);
			b = br.readLine();
		}
		JSONObject json = JSONObject.fromObject(sb.toString());
		System.out.println(json);
		System.out.println("===========================");
//		int itemsSize = json.getJSONArray("resourceSets").getJSONObject(0)
//				.getJSONArray("resources").getJSONObject(0)
//				.getJSONArray("routeLegs").getJSONObject(0)
//				.getJSONArray("itineraryItems").size();
		
		String point = json.getJSONArray("resourceSets").getJSONObject(0).
		getJSONArray("resources").getJSONObject(0).getJSONObject("point").get("coordinates").toString();
		String[] coordinates = point.split(",");
		
		//.getJSONArray("point").getJSONObject(0).toString();*/
		System.out.println(Arrays.toString(coordinates));
		System.out.println(point.toString());
		coordinates[0] = coordinates[0].substring(1);
		coordinates[1] = coordinates[1].substring(0, coordinates[1].indexOf("]"));
		
		System.out.println("latitude:"+ coordinates[0]);
		System.out.println("longtitude:"+ coordinates[1]);


	}
}
	
	

}
